import GameConfig from "../GameSpecial/GameConfig";

export default class http_request {

    public static url_ad = GameConfig.url_ad;
    public static url_login = GameConfig.url_login;
    public static url_gamelevel = GameConfig.url_gamelevel;
    public static url_buy = GameConfig.url_buy;

    private constructor() { }

    public static postRequest(url: string, _data: any, _callback?: (params: any) => void) {
        console.log('postRequest --->', url);
        let http = new XMLHttpRequest();
        http.open("POST", url, true); //初始化请求
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        let str = '';
        for (let a in _data) {
            str += a + "=" + encodeURIComponent(_data[a]) + '&';
        }
        str = str.substr(0, str.length - 1);
        http.send(str); //JSON.stringify(_data)
        http.onreadystatechange = () => {
            let state = http.readyState; //返回服务器的状态
            let status = http.status;
            if (state == 4 && status == 200) {
                let response: string = http.responseText; //返回的信息是一个字符串
                let data = JSON.parse(response); //解析字符串
                _callback && _callback(data);
            }
        };
    }

    public static get(url, _data, _callback) {
        let xhr = new XMLHttpRequest();
        xhr.timeout = 10 * 1000;
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (this.readyState === 4 && (this.status >= 200 && this.status < 300)) {
                let respone = xhr.responseText;
                if (!respone) console.log("httperror", respone);
                let resp = JSON.parse(respone);
                _callback(resp);
            }
        };
        let str = '';
        for (let a in _data) {
            str += a + "=" + _data[a] + '&';
        }
        str = str.substr(0, str.length - 1);
        xhr.send(str);
    }
}




